//创建用户相关的小仓库
import { defineStore } from 'pinia'
import { reqLogin, reqUserInfo, reqLogout } from '@/api/user'
import type { UserState } from './types/type'
import { SET_TOKEN, GET_TOKEN, REMOVE_TOKEN } from '@/utils/token'
//引入路由
import { constantRoute } from '@/router/routers'
import type {
  loginFormData,
  loginResponseData,
  userInfoResponseData,
} from '@/api/user/type'

//创建用户小仓库

const useUserStore = defineStore('User', {
  //小仓库存储数据的地方
  state: (): UserState => {
    return {
      token: GET_TOKEN(), //用户唯一标识token
      menuRoutes: constantRoute,
      username: '',
      avatar: '',
    }
  },
  //异步|逻辑的地方
  actions: {
    //用户登录的方法
    async userLogin(data: loginFormData) {
      const result: loginResponseData = await reqLogin(data)
      //登录请求：成功200->token
      if (result.code == 200) {
        this.token = result.data as string
        console.log(result.data)
        //本地持久化存储token
        SET_TOKEN(result.data as string)
        //能保证当前的async函数返回一个成功的 promise
        return 'ok'
      } else {
        //登录请求：失败201->登录失败错误的信息
        return Promise.reject(new Error(result.data))
      }
    },
    //获取用户信息
    async userInfo() {
      const result: userInfoResponseData = await reqUserInfo()
      //获取用户信息成功，存储一下用户的数据
      if (result.code == 200) {
        this.username = result.data.name
        this.avatar = result.data.avatar
        return 'ok'
      } else {
        return Promise.reject(new Error(result.message))
      }
    },
    //退出登录
    async userLogout() {
      // 退出登录请求
      const result: any = await reqLogout()
      if (result.code == 200) {
        //目前没有mock接口：退出登录接口（通知服务器本地用户唯一标识失效）
        this.token = ''
        this.username = ''
        this.avatar = ''
        REMOVE_TOKEN()
        return 'ok'
      } else {
        return Promise.reject(new Error(result.message))
      }
    },
  },
  getters: {},
})
//对外暴露获取小仓库的方法
export default useUserStore
